package com.iwhalecloud.bss.kite.cucc.service.shoppingcart.check.impl;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.SnowflakeUtils;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.CuccQryResultConfigCache;
import com.iwhalecloud.bss.kite.cucc.dataservice.entity.QueryResultConfig;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.QueryResultConfigMapper;
import com.iwhalecloud.bss.kite.cucc.service.shoppingcart.check.ILocalCheckService;
import com.ztesoft.bss.common.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Objects;

/**
 * @author linjj
 * version 1.0 2022/2/24
 */
@Service
public class LocalCheckService implements ILocalCheckService {

    @Autowired
    private QueryResultConfigMapper queryResultConfigMapper;

    @Override
    public DataResult resultConfig(Integer check) {
        String staffId = ContextUtil.getSimpleLoginInfo().getUserId().toString();

        Example example = new Example(QueryResultConfig.class);
        example.createCriteria().andEqualTo("staffId", staffId);

        int result = 0;
        QueryResultConfig queryResultConfig = queryResultConfigMapper.selectOneByExample(example);
        if (Objects.isNull(queryResultConfig)) {
            queryResultConfig = new QueryResultConfig();
            queryResultConfig.setConfigId(SnowflakeUtils.generateId());
            queryResultConfig.setCheckResult(check);
            queryResultConfig.setStaffId(Long.parseLong(staffId));
            result = queryResultConfigMapper.insert(queryResultConfig);

        }
        else {
            queryResultConfig.setCheckResult(check);
            result = queryResultConfigMapper.updateByExampleSelective(queryResultConfig, example);
        }
        if (result > 0) {
            CuccQryResultConfigCache.put(staffId, queryResultConfig);
        }
        return ErrorConsts.SUCCESS.getResult(result);
    }

    @Override
    public DataResult getResultConfig() {
        String staffId = ContextUtil.getSimpleLoginInfo().getUserId().toString();

        return ErrorConsts.SUCCESS.getResult(CuccQryResultConfigCache.getQueryResutConfig(staffId));
    }
}
